package com.yj.springbootstudy.mulThread.demo;

/**
 * 保护性暂停模式
 */
public class Demo02 {

    public static void main(String[] args) {

    }
}

class Pause{

    private Object response;


    public Object get(){
        synchronized (this){
            while (response == null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    // 带超时时间的获取
    public Object getByTime(long time){
        long begin = System.currentTimeMillis();
        synchronized (this){
            long passed = 0;
            while (response == null){
                long waitTime = time - passed;

                if (waitTime<0){
                    break;
                }
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passed = System.currentTimeMillis() - time;
            }
            return response;
        }
    }


    public void consume(Object response){
        synchronized (this){
            this.response = response;
            this.notifyAll();
        }
    }

}
